<!doctype html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>荣光影视</title>
    <!-- Template CSS -->
    <link rel="stylesheet" th:href="@{/static/css/bootstrap.min.css}">
    <link rel="stylesheet" th:href="@{/static/css/style-starter.css}">
    <script th:src="@{/static/layui.js}"></script>
    <link rel="stylesheet" type="text/css" th:href="@{/static/css/xcConfirm.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/static/css/font-awesome.min.css}"/>
    <link th:href="@{/static/css/style2.css}" rel="stylesheet"/>
    <link rel="stylesheet" th:href="@{/static/css/flexslider.css}"/>

    <style>
        li {
            list-style-type: none;
        }

        .mydiv:hover {
            width: 100%; /* 保持宽度响应式 */
            border: #909090 1px solid;
            background: #fff;
            color: #333;
            transform: translateY(-5px); /* 添加轻微上浮效果 */
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            transition: all 0.2s ease-in-out;
        }

        a {
            cursor: pointer;
            text-decoration: none;
        }

        a:link, a:visited {
            text-decoration: none;
        }

        /* 让所有卡片高度一致，并使内容垂直分布 */
        .card.mydiv {
            height: 100%;
            display: flex;
            flex-direction: column;
        }

        .card.mydiv .card-body {
            flex-grow: 1; /* 让body部分填充剩余空间 */
            display: flex;
            flex-direction: column;
            justify-content: space-between; /* 内容两端对齐 */
        }

        /* 粉丝/关注列表样式 */
        #friendsList .list-group-item.active {
            background-color: #ff6e6e;
            border-color: #ff6e6e;
        }

        .unfollow-btn {
            color: #dc3545;
            cursor: pointer;
        }

        .unfollow-btn:hover {
            text-decoration: underline;
        }
    </style>
</head>

<body>
<input type="hidden" id="userId" th:value="${session.user.userId}"/>

<!-- header -->
<header id="site-header" class="w3l-header fixed-top">
    <!--/nav-->
    <nav class="navbar navbar-expand-lg navbar-light fill px-lg-0 py-0 px-3">
        <div class="container">
            <h1><a class="navbar-brand" href="#">荣光影视 </a></h1>
            <button class="navbar-toggler collapsed" type="button" data-toggle="collapse"
                    data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
                    aria-label="Toggle navigation">
                <span class="fa icon-expand fa-bars"></span>
                <span class="fa icon-close fa-times"></span>
            </button>

            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav ml-auto">
                    <li class="nav-item active"><a class="nav-link" th:href="@{/user/toIndex}">主页</a></li>
                </ul>

                <!--/search-right-->
                <div class="search-right">
                    <a href="#search" class="btn search-hny mr-lg-3 mt-lg-0 mt-4" title="search">搜索<span
                            class="fa fa-search ml-3" aria-hidden="true"></span></a>
                    <div id="search" class="pop-overlay">
                        <div class="popup">
                            <form th:action="@{/video/search}" method="post" class="search-box">
                                <input type="search" placeholder="Search your Keyword" name="videoTitle"
                                       required="required" autofocus="">
                                <button type="submit" class="btn"><span class="fa fa-search" aria-hidden="true"></span>
                                </button>
                            </form>
                        </div>
                        <a class="close" href="#close">×</a>
                    </div>
                </div>
            </div>

            <div class="mobile-position">
                <nav class="navigation">
                    <div class="theme-switch-wrapper">
                        <label class="theme-switch" for="checkbox">
                            <input type="checkbox" id="checkbox">
                            <div class="mode-container"><i class="gg-sun"></i><i class="gg-moon"></i></div>
                        </label>
                    </div>
                </nav>
            </div>

            <div th:unless="${session.user}">
                <a th:href="@{/user/toLogin}" class="btn btn-primary btn-lg"
                   style="height: 38px;font-size: 14px;">登录</a>
            </div>
            <div th:if="${session.user}">
                <button class="layui-btn layui-btn-primary" id="demo4">
                    <span th:text="${session.user.userName}"></span>
                    <i class="layui-icon layui-icon-more-vertical layui-font-12"></i>
                </button>
            </div>
        </div>
    </nav>
</header>
<!-- //header -->

<section class="container" style="margin-top: 100px;">
    <!-- Navigation Tabs -->
    <ul class="nav nav-tabs mb-4">
        <li class="nav-item"><a class="nav-link" href="#" id="collectionButton">收藏</a></li>
        <li class="nav-item"><a class="nav-link" href="#" id="recordButton">播放记录</a></li>
        <li class="nav-item"><a class="nav-link" href="#" id="fdVideoButton">关注</a></li>
        <li class="nav-item"><a class="nav-link" href="#" id="VideoButton">粉丝</a></li>
        <li class="nav-item"><a class="nav-link" href="#" id="manageVideoButton">管理视频</a></li>
    </ul>

    <!-- Content Panels -->
    <div id="content-panels">
        <!-- 播放记录 -->
        <div class="row" id="record" style="display:none;"></div>
        <!-- 收藏 -->
        <div class="row" id="collection" style="display:none;"></div>
        <!-- 关注的视频 -->
        <div class="row" id="fdVideoPage" style="display:none;">
            <div class="col-lg-3">
                <div class="list-group" id="friendsList"></div>
            </div>
            <div class="col-lg-9">
                <div class="row" id="fdvideo"></div>
            </div>
        </div>
        <!-- 粉丝列表 -->
        <div class="panel panel-default" id="fans-panel" style="display:none;">
            <div class="panel-heading"><h4>我的粉丝</h4></div>
            <div class="panel-body">
                <div class="list-group" id="fans-list">加载中...</div>
            </div>
        </div>
        <!-- 管理视频 -->
        <div id="manageVideo" style="display:none;">
            <h4>我的视频管理</h4>
            <div class="row" id="myVideoList"></div>
        </div>
    </div>
</section>
</body>

<!-- SCRIPTS -->
<script th:src="@{/static/js/jquery.min.js}"></script>
<script th:src="@{/static/js/bootstrap.min.js}"></script>
<script th:src="@{/static/js/xcConfirm.js}" type="text/javascript" charset="utf-8"></script>
<script th:src="@{/static/js/common.js}"></script>
<script th:src="@{/static/js/theme-change.js}"></script>
<script th:src="@{/static/js/jquery.magnific-popup.min.js}"></script>
<script th:src="@{/static/js/easyResponsiveTabs.js}"></script>

<script type="text/javascript">
    $(document).ready(function () {

        // =================================================================
        // 1. 核心逻辑：数据加载与界面渲染
        // =================================================================

        const userId = $('#userId').val();

        // 统一的面板切换函数
        function switchPanel(panelToShow) {
            $('#content-panels > div').hide();
            $(panelToShow).show();
        }

        // 通用的视频卡片渲染函数
        function renderVideoCards(targetSelector, videos, type = 'friend') {
            const container = $(targetSelector);
            if (!videos || videos.length === 0) {
                container.html('<div class="col-12 text-center p-5"><h4>暂无内容</h4></div>');
                return;
            }

            const videoCardsHtml = videos.map(video => {
                const videoInfo = video.videoInfo ? video.videoInfo.substring(0, 30) + (video.videoInfo.length > 30 ? '...' : '') : '无描述';
                const editDate = new Date(video.editDate).Format("yyyy-MM-dd hh:mm:ss");
                const thunmbnailUrl = video.thunmbnailUrl || '/static/images/default-thumbnail.jpg';

                let actionButton = '';
                let cardInfo = `状态：${video.videoState?.stateName || '未知'}`;

                if (type === 'collection') {
                    actionButton = `<a role="menuitem" tabindex="-1" class="dropdown-item delete-action" data-type="collection" data-id="${video.videoId}">删除收藏</a>`;
                    cardInfo = `收藏于：${editDate}`;
                } else if (type === 'record') {
                    actionButton = `<a role="menuitem" tabindex="-1" class="dropdown-item delete-action" data-type="record" data-id="${video.videoId}">删除记录</a>`;
                    cardInfo = `观看于：${editDate}`;
                }

                // 管理视频卡片模板
                if (type === 'manage') {
                    return `
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4" id="video-card-${video.videoId}">
                        <div class="card mydiv">
                             <img style="cursor:pointer;" class="card-img-top" src="${thunmbnailUrl}" onclick="window.open('/video/videoPlay?videoId=${video.videoId}')" alt="${video.videoTitle}">
                            <div class="card-body">
                                <div>
                                    <h5 class="card-title font-weight-bold">${video.videoTitle}</h5>
                                    <p class="card-text small text-muted">简述：${videoInfo}</p>
                                    <p class="card-text small">状态：${video.videoState?.stateName || '未知'}</p>
                                    <p class="card-text small">观看：${video.viewNum || 0} | 点赞：${video.ppNum || 0}</p>
                                    <p class="card-text small"><time>上传于：${editDate}</time></p>
                                </div>
                                <div class="btn-group mt-2 w-100" role="group">
                                    <button type="button" class="btn btn-primary btn-sm view-video" data-id="${video.videoId}">查看</button>
                                    <button type="button" class="btn btn-warning btn-sm edit-video" data-id="${video.videoId}">编辑</button>
                                    <button type="button" class="btn btn-danger btn-sm delete-action" data-type="my-video" data-id="${video.videoId}">删除</button>
                                </div>
                            </div>
                        </div>
                    </div>`;
                }

                // 其他类型视频卡片模板
                return `
                <div class="col-lg-3 col-md-4 col-sm-6 mb-4" id="video-card-${type}-${video.videoId}">
                    <div class="card mydiv">
                        <img style="cursor:pointer;" class="card-img-top" src="${thunmbnailUrl}" onclick="window.open('/video/videoPlay?videoId=${video.videoId}')" alt="${video.videoTitle}">
                        <div class="card-body">
                            <div>
                                <h5 class="card-title font-weight-bold">${video.videoTitle}</h5>
                                <p class="card-text small text-muted">简述：${videoInfo}</p>
                            </div>
                            <div class="d-flex justify-content-between align-items-center mt-2">
                                <span class="small text-muted">${cardInfo}</span>
                                ${actionButton ? `
                                <div class="dropup">
                                    <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown">操作</button>
                                    <div class="dropdown-menu dropdown-menu-right">
                                        ${actionButton}
                                    </div>
                                </div>` : ''}
                            </div>
                        </div>
                    </div>
                </div>`;
            }).join('');

            container.html(videoCardsHtml);
        }

        // 通用 AJAX 加载函数
        function loadData(url, params, successCallback) {
            const targetContainer = params.container;
            if (targetContainer) $(targetContainer).html('<div class="col-12 text-center p-5"><h4>加载中...</h4></div>');

            $.ajax({
                url: url,
                type: "GET",
                data: params.data,
                dataType: "JSON",
                success: successCallback,
                error: function () {
                    window.wxc.xcConfirm("数据加载失败", window.wxc.xcConfirm.typeEnum.error);
                    if (targetContainer) $(targetContainer).html('<div class="col-12 text-center p-5 text-danger"><h4>加载失败，请重试</h4></div>');
                }
            });
        }


        // =================================================================
        // 2. 各个 Tab 的具体加载逻辑
        // =================================================================

        $('.nav-tabs .nav-link').on('click', function (e) {
            e.preventDefault();
            $('.nav-tabs .nav-link').removeClass('active');
            $(this).addClass('active');
        });

        $('#collectionButton').click(function () {
            switchPanel('#collection');
            if ($('#collection').is(':empty')) {
                loadData("/collection/getAllCollection", {container: '#collection'}, (res) => renderVideoCards('#collection', res.data, 'collection'));
            }
        });

        $('#recordButton').click(function () {
            switchPanel('#record');
            if ($('#record').is(':empty')) {
                loadData("/record/getAllRecord", {container: '#record'}, (res) => renderVideoCards('#record', res.data, 'record'));
            }
        });

        $('#fdVideoButton').click(function () {
            switchPanel('#fdVideoPage');
            if ($('#friendsList').is(':empty')) {
                loadData("/focus/focusedList", {}, (res) => {
                    const friendsHtml = (res.data || []).map(friend => `
                    <a href="#" class="list-group-item list-group-item-action friend-item" data-friend-id="${friend.userId}">
                        <div class="d-flex w-100 justify-content-between align-items-center">
                            <h6 class="mb-1">${friend.userName}</h6>
                            <small class="unfollow-btn text-danger" data-following-id="${friend.userId}">取消关注</small>
                        </div>
                        <small class="text-muted">注册于：${new Date(friend.registerDate).Format("yyyy-MM-dd")}</small>
                    </a>`).join('');
                    $('#friendsList').html(friendsHtml || '<div class="list-group-item">暂无关注</div>');
                });
            }
        });

        $("#fdVideoButton").click(function () {
            $("#fdVideoPage").show();
            $("#record").hide();
            $('#collection').hide();
            $('#fans-panel').hide(); // 新增：隐藏粉丝面板
            if (fdVideo_signal == false) {
                myFriends("/focus/focusedList", '#friendsList', 'fd', null)
                fdVideo_signal = true;
            }
        });

        // 合并原本裸露在页面末尾的 JS 代码
        $(document).ready(function () {
            var userId = $('#userId').val();
            // 点击“粉丝”按钮时显示粉丝列表
            $('#VideoButton').click(function () {
                $('#fans-panel').show();
                $('#fdVideoPage').hide(); // 隐藏关注界面
                $('#record').hide();      // 隐藏播放记录
                $('#collection').hide(); // 隐藏收藏
                loadFansList(userId);
            });
        });

        function loadFansList(userId) {
            $.get('/api/fans/userlist/' + userId, function (fansList) {
                var html = '';
                if (fansList.length === 0) {
                    html = '<div>暂无粉丝</div>';
                } else {
                    fansList.forEach(function (fan) {
                        html += '<div class="fan-item" style="margin-bottom:8px;">';
                        html += '<span>' + (fan.userName || ('用户' + fan.userId)) + '</span>';
                        html += '</div>';
                    });
                }
                $('#fans-list').html(html);
            });
        }

        $('#manageVideoButton').click(function () {
            switchPanel('#manageVideo');
            if ($('#myVideoList').is(':empty')) {
                loadData("/video/getAllVideoListByUserId", {
                    data: {userId: userId},
                    container: '#myVideoList'
                }, (res) => renderVideoCards('#myVideoList', res.data, 'manage'));
            }
        });


        // =================================================================
        // 3. 动态绑定事件 (使用事件委托)
        // =================================================================

        $('#friendsList').on('click', '.friend-item', function (e) {
            e.preventDefault();
            const friendId = $(this).data('friend-id');
            $(this).addClass('active').siblings().removeClass('active');
            loadData("/video/getVideoListByUserId", {
                data: {userId: friendId},
                container: '#fdvideo'
            }, (res) => renderVideoCards('#fdvideo', res.data, 'friend'));
        });

        $('#friendsList').on('click', '.unfollow-btn', function (e) {
            e.stopPropagation();
            const followingId = $(this).data('following-id');
            const friendItem = $(this).closest('.friend-item');
            $.post("/api/socialFollow/unfollow", {followerId: userId, followingId: followingId}, (res) => {
                if (res === "success") {
                    window.wxc.xcConfirm("取消关注成功", window.wxc.xcConfirm.typeEnum.success);
                    friendItem.remove();
                    if ($('#friendsList').children().length === 0) {
                        $('#friendsList').html('<div class="list-group-item">暂无关注</div>');
                    }
                } else {
                    window.wxc.xcConfirm("操作失败", window.wxc.xcConfirm.typeEnum.error);
                }
            });
        });

        $('body').on('click', '.delete-action', function () {
            const type = $(this).data('type');
            const id = $(this).data('id');
            const urls = {
                'collection': '/collection/deleteCollection',
                'record': '/record/removeRecord',
                'my-video': '/video/delete'
            };
            const cardSelector = `#video-card-${type === 'my-video' ? '' : type + '-'}${id}`;
            if (!urls[type]) return;
            window.wxc.xcConfirm("确定要删除吗？", window.wxc.xcConfirm.typeEnum.confirm, {
                onOk: function () {
                    $.post(urls[type], {videoId: id})
                        .done(() => {
                            window.wxc.xcConfirm("删除成功", window.wxc.xcConfirm.typeEnum.success);
                            $(cardSelector).remove();
                        })
                        .fail(() => window.wxc.xcConfirm("删除失败", window.wxc.xcConfirm.typeEnum.error));
                }
            });
        });

        // 点击“查看”按钮，功能与点击图片一致
        $('body').on('click', '.view-video', function () {
            const videoId = $(this).data('id');
            window.open(`/video/videoPlay?videoId=${videoId}`);
        });

        $('body').on('click', '.edit-video', function () {
            const videoId = $(this).data('id');
            window.location.href = '/video/toAddVideo?videoId=' + videoId;
        });

    });
</script>

</html>